package com.zoe.onelink.auth.token.processor.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.zoe.onelink.auth.property.OnelinkAuthProperties;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;
import java.util.Map;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2023</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2023-01-04
 */
public class OnelinkLocalCachedRedisTokenInfoProcessor extends OnelinkRedisTokenInfoProcessor {


    private final Cache<String, Map<String, Object>> localCache;


    public OnelinkLocalCachedRedisTokenInfoProcessor(RedisTemplate<String, Object> redisTemplate,
                                                     OnelinkAuthProperties onelinkAuthProperties) {
        super(redisTemplate);
        if (onelinkAuthProperties.getLocalCache().isEnabled()) {
            this.localCache = initCache(onelinkAuthProperties.getLocalCache().getExpiredTime().getSeconds());
        } else {
            this.localCache = null;
        }
    }

    private Cache<String, Map<String, Object>> initCache(long expiredSeconds) {
        return Caffeine.newBuilder()
                .expireAfterWrite(Duration.ofSeconds(expiredSeconds))
                .maximumSize(8192)
                .softValues().build();
    }

    @Override
    public Map<String, Object> process(String onelinkToken) {
        if (this.localCache == null) {
            return super.process(onelinkToken);
        }
        return this.localCache.get(onelinkToken, super::process);
    }
}
